(function() {
    /**
     * 调用 content 为当前文章所在Dom
     *  <script>
            $('.content').page();
        </script>
     **/
    
    
        function TurnPage(wrap) {
            this.wrap = wrap;
            this.page = 1;
        }

        TurnPage.prototype.init = function () {
            let config  = this.getHref();
            this.fillHtml(config);
            this.event();
            this.toolPage();
        };

        TurnPage.prototype.getHref = function () {
            let nexthref = $("a").filter(function(){
		        return $(this).text().indexOf("下一页") > -1 || $(this).text().indexOf("下一章") > -1;
            });
            let title = $("title").text();
            let prvhref = $("a").filter(function(){
		        return $(this).text().indexOf("上一页") > -1 || $(this).text().indexOf("上一章") > -1;
            });
            let menu = $("a").filter(function(){
		        return $(this).text().indexOf("目录") > -1;
            });
            return {"下一章":nexthref.attr("href") ?? '###',"上一章":prvhref.attr("href") ?? '###',"目录":menu.attr("href") ?? '###',"标题":title};
        };

        TurnPage.prototype.getX = function (e) {
            e = e || window.event;
            return e.pageX || e.clientX + document.body.scroolLeft;
        };

        TurnPage.prototype.getY = function (e) {
            e = e || window.event;
            return e.pageY || e.clientY + document.body.scroolTop;
        };

        TurnPage.prototype.event = function () {
            $wrapper = $("#fillPage");
            var isMoving = false;
            var firstTouch;
            var touch = {};
            var startLeft = 0;
            window.ye = $(document).width() / $(window).width();
            $(".pageSize-1").html(Math.ceil(ye));
            window.dye = $(document).width();
            window.wye = $(window).width();
            
            let pageEventFunc = (event, type = false,pageX = this.getX(event),pageY = this.getY(event)) => {
                this.toolPage("hidden")
                if (type === false) {
                    //click 事件的处理
                    x2 = pageX;
                    y2 = pageY;
                    if (x2 > $(window).width() / 2 || y2 > $(window).height() / 2) {
                        startLeft++;
                    } else {
                        startLeft--;
                    }
                } else {
                    //滑动事件的处理
                    if (type === 1200) { //下一页
                        startLeft++;
                    } else if (type === 1300) { // 上一页
                        startLeft--;
                    } else {
                        return false;
                    }
                }
                

                if (startLeft * wye >= dye) {
                    startLeft--;
                    $wrapper.css({
                        "-webkit-transform": "translateX(" + -startLeft * wye + "px)",
                        transform: "translateX(" + -startLeft * wye + "px)"
                    });
                    
                    this.getColor().autopage === true && window._wdasdasdye===1 && $("#hrefprev")[0].click();
                    
                    if(window._wdasdasdye !== 1){
                        window._wdasdasdye = 1;
                    }
                    
                    return false;
                } else if (startLeft * wye < wye) {
                    startLeft = 0;
                    $(".pageSize-2").html((startLeft + 1));
                    $wrapper.css({
                        "-webkit-transform": "translateX(0px)",
                        transform: "translateX(0px)"
                    });
                    this.getColor().autopage === true && window._wdasdasdye===1 && $("#hrefnext")[0].click();
                    if(window._wdasdasdye !== 1){
                        window._wdasdasdye = 1;
                    }
                    return false;
                } else {
                    $(".pageSize-2").html((startLeft + 1));
                }
                $wrapper.css({
                    "-webkit-transform": "translateX(" + -startLeft * wye + "px)",
                    transform: "translateX(" + -startLeft * wye + "px)"
                });
                this.page = startLeft;
            };

            document.getElementById("fillPageBox").addEventListener("click", event => {
                x2 = this.getX(event);
                windowWidth = $(window).width();
                if(Math.abs(windowWidth/2 - x2) < windowWidth/12){
                    this.toolPage();
                }else{
                    pageEventFunc(event);
                }
                
            });

            document.getElementById("fillPageBox").addEventListener("touchmove", event => {
                event.stopPropagation && event.stopPropagation();
                event.preventDefault && event.preventDefault();
            });

            let pageX = [0, 0];

            document.getElementById("fillPageBox").addEventListener("touchstart", event => {
                event.stopPropagation && event.stopPropagation();
                event.preventDefault && event.preventDefault();
                pageX[0] = event.targetTouches[0]["pageX"];
            });


            document.getElementById("fillPageBox").addEventListener("touchend", event => {
                event.stopPropagation && event.stopPropagation();
                event.preventDefault && event.preventDefault();
                pageX[1] = event.changedTouches[0]["pageX"];
                pageY = event.changedTouches[0]["pageY"];

                if (pageX[0] > pageX[1]) {
                    pageEventFunc(event, 1200);
                } else if (pageX[0] < pageX[1]) {
                    pageEventFunc(event, 1300);
                }else{
                    x2 = pageX[1];
                    windowWidth = $(window).width();
                    if(Math.abs(windowWidth/2 - x2) < windowWidth/12){
                        this.toolPage();
                    }else{
                        pageEventFunc(event,false,pageX[1],pageY);
                    }
                }
            });
        };

        TurnPage.prototype.fillHtml = function (config) {
            console.log(config);
            let html = $(this.wrap).text();
            let body = $("body");
            body.empty();
            body.append("<div class='fillPage' id='fillPageBox'><div id='fillPage'></div></div>");
            let page = $("#fillPage");
            body.append(`<style>
            body,p{
                padding: 0px;
                margin: 0px;
            }
            .menu-ddd{
                position: fixed;
                right: 0px;
                width: 100vw;
                color: rgb(0 0 0);
                background: rgb(0 0 0 / 85%);
                transition: height 0.1s ease 0s;
                box-shadow: 4px 0px 13px 3px rgb(94 94 94 / 82%);
                overflow: hidden;
                display: flex;
                font-size:14px;
                flex-direction: column;
                justify-content: space-evenly;
                z-index:99999;
            }
            .menu-ddd div a{
                color: #fff;
                text-decoration: none;
                width: 33%;
                text-align: center;
            }
            .menu-ddd div{
                display: flex;
                color: #fff;
                text-align: center;
                justify-content: center;
                padding: 10px 0px;
            }
            .menu-ddd div span{
                text-align: center;
            }
            .menu-ddd div span p button{
                width: 12vw;
                margin: 0px 6vw 0 0;
                background: rgb(251 251 251 / 12%);
                color: #fff;
                border: 0px;
                border-radius: 6px;
                border: 1px solid #525252;
                margin-top: 3vw;
                outline: none;
            }
            .menu-ddd div span p{
                display: flex; 
                flex-direction: row;
                justify-content: space-between;
                align-items: flex-end;
            }
            #fillPage{
                overflow: visible;
                height: 90%;
                columns: calc(100vw - 9vw) 1;
                column-gap: 18vw;
                padding: 9vw;
                transition: transform 0.1s ease 0s;
                line-height: 26px;
                user-select: none;
                font-size: 14px;
                white-space:normal;
                word-break:break-all;
                word-wrap:break-word;
            }
            button.select{
                border: 1px solid #fff597 !important;
            }
            </style>`);
            
            page.html(html);
            
            $(".fillPage").append(`
            <span class='pageSize' id='pageNumber' style='position: fixed;top: 2vw;right: 2vw;color: #555;'>
            第<span class='pageSize-2'>1</span>页/共<span class='pageSize-1'></span>页
            </span>`);
            
            $("body").off("click","#pageNumber").on("click","#pageNumber",e=>{
                this.toolPage();
            });
            
            
            $("#fillPageBox").parent().append(`<span class='pageMenuTop menu-ddd' style='top: 0px;height:0;'>
            <div><span>${config["标题"]}</span></div>
            <div>
                <a id='hrefprev' href='${config["上一章"]}'>上一章</a>
                <a href='${config["目录"]}'>目录</a>
                <a id='hrefnext' href='${config["下一章"]}'>下一章</a>
            </div>
            
            </span><span class='pageMenuButtom menu-ddd' style='bottom: 0px;height:0;'>
            <div>
                <a href='${config["上一章"]}'>上一章</a>
                <a href='${config["目录"]}'>目录</a>
                <a href='${config["下一章"]}'>下一章</a>
            </div>
            <div>
                <span>
                    <p> 
                    <button class='buttonConfig font'>+</button>
                    <button class='fontsizeText' style='color: #ffb4b4;width: 80px;background: transparent;'>14</button>
                    <button class='buttonConfig font'>-</button>
                    字体 
                    </p>
                    <p> 
                    <button class='buttonConfig line'>+</button>
                    <button class='lineheightText' style='color: #ffb4b4;width: 80px;background: transparent;'>26</button>
                    <button class='buttonConfig line'>-</button>
                    排版 
                    </p>
                    <p> 
                    <button class='buttonConfig color'>黄</button>
                    <button class='buttonConfig color'>白</button>
                    <button class='buttonConfig color'>绿</button>
                    <button class='buttonConfig color'>黑</button>
                    配色 
                    </p>
                    <p> 
                    <button class='buttonConfig page'>是</button>
                    <button class='buttonConfig page'>否</button>
                    <button class='buttonConfig read'>阅读</button> 
                    自动翻页 
                    </p>
                </span>
            </div>
            </span>`);
            
            this.addConfig();
            this.$wrapper = $("#fillPage");
        }
        
        
        
        TurnPage.prototype.toolPage = function(hidden){
            if($(".pageMenuTop").css("height") == "0px" && hidden != "hidden"){
                $(".menu-ddd").show();
                $(".pageMenuTop").css("height","10vh");
            }else{
                $(".menu-ddd").hide();
                $(".pageMenuTop").css("height","0px");
            }
            
            if($(".pageMenuButtom").css("height") == "0px" && hidden != "hidden"){
                $(".pageMenuButtom").css("height","25vh");
            }else{
                $(".pageMenuButtom").css("height","0px");
            }
            
            
            
            $("body").off("click",".buttonConfig").on("click",".buttonConfig", event => {
                let type,value;
                let config = this.getColor();
                switch (event.target.innerText) {
                    case '+':
                        if($(event.target).hasClass("font")){
                            type = "fontsize";
                        }else if($(event.target).hasClass("line")){
                            type = "lineheight";
                        }
                        config[type] ++;
                        break;
                    case '-':
                        if($(event.target).hasClass("font")){
                            type = "fontsize";
                        }else if($(event.target).hasClass("line")){
                            type = "lineheight";
                        }
                        config[type] --;
                        break;
                    
                    default:
                        if($(event.target).hasClass("color")){
                            type = "color";
                            config[type] = event.target.innerText
                        }else if($(event.target).hasClass("page")){
                            type = "autopage";
                            config[type] = event.target.innerText === "是" ? true : false;
                        }else if($(event.target).hasClass("read")){
                            type = "read";
                            config[type] = !config[type];
                        }
                        // code
                }
                
                this.setColor(config);
                
                this.addConfig();
            });

        }
        
        let _pageToolColorConfig_data = {fontsize:14,lineheight:26,color:"绿",autopage:false,read:true};

        TurnPage.prototype.addConfig = function(key,value){
            if(this.getColor()){
                _pageToolColorConfig_data = this.getColor();
            }
            
            let color = {"黄":["#ddd1b7","#1a1a1a"],"黑":["#3e4245","#ddd"],"绿":["#C7EDCC","rgb(58, 60, 47)"],"白":["#ffffff","#1c1c1c"]};
            if(key){
                _pageToolColorConfig_data[key] = value;
            }
            
            this.setColor(_pageToolColorConfig_data);
            
            $(".fontsizeText").text(_pageToolColorConfig_data.fontsize);
            $(".lineheightText").text(_pageToolColorConfig_data.lineheight);
            
            $("#fillPage").css({
                "fontSize":_pageToolColorConfig_data.fontsize + "px",
                "lineHeight":_pageToolColorConfig_data.lineheight + "px",
            });
            
            $("body").css({
                "color":color[_pageToolColorConfig_data.color][1],
                "backgroundColor":color[_pageToolColorConfig_data.color][0],
            });
            
            let button = $(".buttonConfig");
            
            button.filter(function(){
                return $(this).text() == _pageToolColorConfig_data.color && $(this).hasClass("color")
            }).addClass("select").siblings().removeClass("select");
                
            if(_pageToolColorConfig_data.autopage){
                button.filter(function(){
                    return $(this).text() == "是" && $(this).hasClass("page")
                }).addClass("select").siblings().removeClass("select");
            }else{
                button.filter(function(){
                    return $(this).text() == "否" && $(this).hasClass("page")
                }).addClass("select").siblings().removeClass("select");
            }
            
            if(_pageToolColorConfig_data.read){
                $(".buttonConfig.read").addClass("select");
            }else{
                $(".buttonConfig.read").removeClass("select");
            }
            
            
        }
        
        TurnPage.prototype.setColor = function(data){
            window.localStorage.setItem("pageToolColorConfig",JSON.stringify(data));
        }

        TurnPage.prototype.getColor = function(hidden){
            return JSON.parse(window.localStorage.getItem("pageToolColorConfig"));
        }

        $.fn.extend({
            page: function () {
                var obj = new TurnPage(this);
                obj.init();
            }
        });
    }
)();



